import { useState, useEffect } from 'react';
import { Form, Notification, Transfer } from 'antd';
import { goBack, componentsMap } from '@/utils/util';
import API from '@/api';
const userComponent = ({ children, id, readOnly }) => {
  const [orgList, setOrgList] = useState([]);
  const [roleList, setRoleList] = useState([]);
  const [targetKeys, setTargetKeys] = useState([]);
  const rangeTypeList = [
    {
      label: '所有范围',
      value: '0',
    },
    {
      label: '省厅',
      value: '1',
    },
    {
      label: '其他单位',
      value: '2',
    },
  ];
  const stateList = [
    {
      label: '有效',
      value: 1,
    },
    {
      label: '禁用',
      value: 2,
    },
  ];
  const formList = [
    {
      name: 'name',
      title: '用户名称',
      type: 'input',
      rules: [
        {
          required: true,
          message: '请输入用户名称',
        },
      ],
    },
    {
      name: 'username',
      title: '用户账号',
      type: 'input',
      rules: [
        {
          required: true,
          message: '请输入用户账号',
        },
      ],
    },
    {
      name: 'phone',
      title: '联系方式',
      type: 'input',
      rules: [
        {
          required: true,
          // pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
          message: '请输入联系方式',
        },
      ],
    },
    {
      name: 'state',
      title: '用户状态',
      type: 'select',
      rules: [
        {
          required: true,
          message: '请选择用户状态',
        },
      ],
      otherProps: {
        options: stateList,
      },
    },
    {
      name: 'orgId',
      type: 'select',
      title: '单位',
      rules: [
        {
          required: true,
          message: '请选择单位',
        },
      ],
      isBlock: true,
      otherProps: {
        options: orgList,
        optionFilterProp: 'label',
        showSearch: true,
      },
    },
    {
      name: 'remark',
      type: 'textarea',
      title: '用户描述',
      isBlock: true,
    },
    {
      name: 'rangeType',
      type: 'select',
      title: '角色范围',
      isBlock: true,
      otherProps: {
        options: rangeTypeList,
        onSelect: (value) => {
          getRoleList(value);
        },
      },
    },
  ];
  const [form] = Form.useForm();

  const initOrgList = () => {
    API.selectOrgListPage({}).then((res) => {
      if (res?.t) {
        const data = res.t.map((x) => ({
          label: x.name,
          value: x.id,
        }));
        setOrgList(data);
      }
    });
  };
  const getRoleList = (rangeType = '0') => {
    API.selectRoleListPage({ rangeType }).then((res) => {
      if (res?.t) {
        const list = res.t.map((el) => ({
          key: el.id,
          title: el.info,
        }));
        setRoleList(list);
      }
    });
  };

  const initDetail = () => {
    API.selectSysUserById({
      id,
    }).then((res) => {
      if (res?.t) {
        const {
          name,
          username,
          phone,
          state,
          remark,
          orgId,
          roleId,
          rangeType,
        } = res.t;
        form.setFieldsValue({
          name,
          username,
          phone,
          state,
          remark,
          rangeType: rangeType + '',
          orgId: +orgId,
          roleId: roleId.split(',').map((x) => +x)
        });
        setTargetKeys(roleId.split(',').map((x) => +x));
      }
    });
  };
  useEffect(() => {
    initOrgList();
    getRoleList();
  }, []);
  useEffect(() => {
    if (id) {
      initDetail();
    } else {
      form.setFieldsValue({
        rangeType: '0',
      });
    }
  }, [id]);
  const submitFn = (values) => {
    values.roleId = values.roleId && values.roleId.join(',');
    let request = API.insertSysUser;
    if (id) {
      values.id = id;
      request = API.updateSysUser;
    }
    const title = !id ? '新增' : '更新';
    request(values).then((res) => {
      if (res) {
        Notification.success({
          message: title + '成功',
        });
        goBack();
      }
    });
  };
  const onChange = (nextTargetKeys) => {
    setTargetKeys(nextTargetKeys);
  };
  return (
    <div className="main-x readOnly-x">
      <Form form={form} onFinish={submitFn}>
        <div className="bgf">
          <div className="ant-form-inline form-x max-x">
            {formList.map((item) => {
              return (
                <Form.Item
                  key={item.name}
                  label={item.title}
                  name={item.name}
                  className={item.isBlock ? 'block' : ''}
                  rules={item.rules}
                >
                  {componentsMap(item.type, item.otherProps, readOnly)}
                </Form.Item>
              );
            })}
            <Form.Item
              label="角色配置"
              name="roleId"
              className="block"
              rules={[{ required: true, message: '请选择角色' }]}
            >
              <Transfer
                listStyle={{
                  width: 400,
                }}
                disabled={readOnly}
                titles={['未选角色', '已选角色']}
                dataSource={roleList}
                targetKeys={targetKeys}
                onChange={onChange}
                render={(item) => item.title}
              />
            </Form.Item>
          </div>
        </div>

        <div className="footer-x max-x">{children}</div>
      </Form>
    </div>
  );
};
export default userComponent;
